<template>
  <div class="dashboard-container">
    <!-- 顶部统计卡片 -->
    <div class="stats-row">
      <div v-for="(stat, index) in topStats" :key="index" class="stat-card">
        <div class="stat-icon" :style="{ backgroundColor: stat.color }"></div>
        <div>
          <div class="stat-label">{{ stat.label }}</div>
          <div class="stat-value">{{ stat.value }}</div>
        </div>
      </div>
    </div>

    <!-- 中间图表区域 -->
    <div class="middle-charts">
      <div class="chart-box">
        <div class="chart-title">新增慢性病患者数</div>
        <div ref="newPatientsChart" class="chart"></div>
      </div>
      <div class="chart-box">
        <div class="chart-title">指标检测异常情况（本周）</div>
        <div ref="abnormalChart" class="chart"></div>
      </div>
    </div>

    <!-- 底部图表区域 -->
    <div class="bottom-charts">
      <div class="chart-box">
        <div class="chart-title">慢病患者分布</div>
        <div ref="diseaseChart" class="chart"></div>
      </div>
      <div class="chart-box">
        <div class="chart-title">慢病患者年龄分布</div>
        <div ref="ageChart" class="chart"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import * as echarts from 'echarts'
const apiUrl = import.meta.env.VITE_APP_API_URL;
// 图表引用
const newPatientsChart = ref(null)
const abnormalChart = ref(null)
const diseaseChart = ref(null)
const ageChart = ref(null)

// 响应式数据
const topStats = ref([])

onMounted(async () => {
  try {
    const response = await axios.get(apiUrl+'/T7/Medical/ManagementOverviewQuery')
    const rawData = response.data.list

    // 数据预处理
    const patients = processPatients(rawData)
    
    // 计算统计数据
    topStats.value = [
      { label: '患者总数', value: patients.length, color: '#5470c6' },
      { label: '高血压患者数', value: countByCondition(patients, 'hypertension'), color: '#91cc75' },
      { label: '糖尿病患者数', value: countByCondition(patients, 'diabetes'), color: '#fac858' },
    ]

    // 初始化图表
    initNewPatientsChart(processNewPatientsData(patients))
    initAbnormalChart(processAbnormalData(patients))
    initDiseaseChart(processDiseaseData(patients))
    initAgeChart(processAgeData(patients))
  } catch (error) {
    console.error('数据获取失败:', error)
  }
})

// 数据处理方法
const processPatients = (rawData) => {
  const patientsMap = new Map()
  rawData.forEach(item => {
    const exist = patientsMap.get(item.patient_Id)
    if (!exist || new Date(item.sign_StartTime) > new Date(exist.sign_StartTime)) {
      patientsMap.set(item.patient_Id, item)
    }
  })
  return Array.from(patientsMap.values())
}

const countByCondition = (patients, field) => 
  patients.filter(p => p[field] === 1).length

const processNewPatientsData = (patients) => {
  const dateMap = patients.reduce((acc, cur) => {
    const date = cur.sign_StartTime.split('T')[0]
    acc[date] = (acc[date] || 0) + 1
    return acc
  }, {})
  
  return {
    dates: Object.keys(dateMap).sort(),
    values: Object.values(dateMap)
  }
}

const processAbnormalData = (patients) => ({
  bloodPressure: countByCondition(patients, 'hypertension'),
  bloodSugar: countByCondition(patients, 'diabetes'),
  bmi: patients.filter(p => p.bmi >= 24).length
})

const processDiseaseData = (patients) => ({
  hypertension: countByCondition(patients, 'hypertension'),
  diabetes: countByCondition(patients, 'diabetes'),
  obesity: patients.filter(p => p.bmi >= 28).length
})

const processAgeData = (patients) => {
  const ranges = ['35以下', '35-40', '40-45', '45-50', '50-55', '55-60', '60+']
  const male = new Array(7).fill(0)
  const female = new Array(7).fill(0)
  
  patients.forEach(p => {
    const age = p.age
    const index = age < 35 ? 0 :
      age < 40 ? 1 :
      age < 45 ? 2 :
      age < 50 ? 3 :
      age < 55 ? 4 :
      age < 60 ? 5 : 6
      
    p.sex ? male[index]++ : female[index]++
  })
  
  return { ranges, male, female }
}

// 图表初始化方法
const initNewPatientsChart = (data) => {
  const chart = echarts.init(newPatientsChart.value)
  chart.setOption({
    xAxis: { type: 'category', data: data.dates },
    yAxis: { type: 'value' },
    series: [{
      data: data.values,
      type: 'line',
      smooth: true,
      areaStyle: { color: '#5470c620' }
    }]
  })
}

const initAbnormalChart = (data) => {
  const chart = echarts.init(abnormalChart.value)
  chart.setOption({
    xAxis: { type: 'value' },
    yAxis: {
      type: 'category',
      data: ['血压异常', '血糖异常', '体质指数']
    },
    series: [{
      data: [data.bloodPressure, data.bloodSugar, data.bmi],
      type: 'bar',
      itemStyle: { color: '#ee6666' }
    }]
  })
}

const initDiseaseChart = (data) => {
  const chart = echarts.init(diseaseChart.value)
  chart.setOption({
    xAxis: { type: 'value' },
    yAxis: {
      type: 'category',
      data: ['高血压', '糖尿病', '肥胖症']
    },
    series: [{
      data: [data.hypertension, data.diabetes, data.obesity],
      type: 'bar',
      itemStyle: { color: '#91cc75' }
    }]
  })
}

const initAgeChart = (data) => {
  const chart = echarts.init(ageChart.value)
  chart.setOption({
    legend: { data: ['男性', '女性'] },
    xAxis: { type: 'category', data: data.ranges },
    yAxis: { type: 'value' },
    series: [
      { name: '男性', type: 'bar', data: data.male, itemStyle: { color: '#5470c6' } },
      { name: '女性', type: 'bar', data: data.female, itemStyle: { color: '#ee6666' } }
    ]
  })
}
</script>

<style scoped>
/* 保持原有样式不变 */
.dashboard-container {
  padding: 20px;
  background: white;
}

.stats-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  display: flex;
  align-items: center;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 8px;
}

.stat-icon {
  width: 40px;
  height: 40px;
  border-radius: 6px;
  margin-right: 15px;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
}

.middle-charts,
.bottom-charts {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-box {
  flex: 1;
  background: #f5f7fa;
  border-radius: 8px;
  padding: 15px;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
}

.chart {
  height: 300px;
}
</style>